package com.gears_software.bbnetwork.activitys;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.WindowFeature;
import org.androidannotations.annotations.sharedpreferences.Pref;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.CountDownTimer;
import android.telephony.TelephonyManager;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;

import com.avos.avoscloud.AVAnalytics;
import com.gears_software.bbnetwork.R;
import com.gears_software.bbnetwork.datas.finders.IBBNetworkFinder;
import com.gears_software.bbnetwork.datas.finders.impl.IBBNetworkFinderImpl;
import com.gears_software.bbnetwork.datas.models.BaseJsonToModel;
import com.gears_software.bbnetwork.datas.models.ResultModel;
import com.gears_software.bbnetwork.datas.models.ReturnCode;
import com.gears_software.bbnetwork.datas.models.UserModel;
import com.gears_software.bbnetwork.utlis.BBNetworkSharedPref_;
import com.gears_software.bbnetwork.utlis.CommonUtils;
import com.gears_software.bbnetwork.utlis.ToastUI;
import com.gears_software.common.net.NetworkUtil;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@SuppressLint("ResourceAsColor")
@EActivity(R.layout.activity_login)
@WindowFeature(Window.FEATURE_NO_TITLE)
public class LoginActivity extends Activity {

	@ViewById
	EditText edit_phone;// 手机号

	@ViewById
	EditText edit_code;// 验证码

	@ViewById
	Button btn_send;// 发送按钮

	@Bean
	ToastUI toast;

	@Pref
	BBNetworkSharedPref_ sp;

	@Bean(IBBNetworkFinderImpl.class)
	IBBNetworkFinder finder;
	TelephonyManager tm;
	TimeCode timeCode;
	String phone = null;
	String code = null;

	@AfterViews
	void onCreate() {
		tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
		phone = sp.phone().get();
		// 如果存有电话号吗，那就直接登录
		if (phone != null && !phone.equals("")) {
			CommonUtils.showDialog(this);
			boolean bol = NetworkUtil.checkNetworkInfo(this);
			if (!bol) {
				showTxt("请检查网络是否正常！");
				return;
			}
			goLogin();
		}
		timeCode = new TimeCode(120000, 1000);
	}

	// 登录按钮
	@Click
	void btn_login() {
		boolean bol = NetworkUtil.checkNetworkInfo(this);
		if (!bol) {
			showTxt("请检查网络是否正常！");
			return;
		}
		code = edit_code.getText().toString().replace(" ", "");
		if (code == null || code.equals("")) {
			showTxt("请填入获取到的验证码");
			return;
		}
		CommonUtils.showDialog(this);
		login();
	}

	// 直接登录
	@Background
	void goLogin() {
		boolean isnet = NetworkUtil.checkNetworkInfo(this);
		if (!isnet) {
			showTxt("请检查网络是否正常！");
			closeDialog();
			return;
		}
		ResultModel<UserModel> res = finder.getLogin(phone, tm.getDeviceId());
		if (res.getReturnCode().equals(ReturnCode.SUCCEED)) {
			UserModel user = res.getResObj();
			sp.userId().put(user.getUserId());
			sp.status().put(user.getStatus());
			sp.hasBankCard().put(user.getHasBankCard());
			sp.hasCashPassword().put(user.getHasCashPassword());
			sp.phone().put(phone);
			Intent intent = new Intent(this, Main2Activity_.class);
			startActivity(intent);
			closeDialog();
			finish();
		} else {
			showTxt(res.getMessage());
			closeDialog();
		}

	}

	@UiThread
	void closeDialog() {
		CommonUtils.closeDialog();
	}

	// 注册加登录
	@Background
	void login() {
		ResultModel<UserModel> res = finder.getVerifyRegistCode(phone,
				tm.getDeviceId(), code);
		if (res.getReturnCode().equals(ReturnCode.SUCCEED)) {
			UserModel user = res.getResObj();
			sp.userId().put(user.getUserId());
			sp.status().put(user.getStatus());
			sp.hasBankCard().put(user.getHasBankCard());
			sp.hasCashPassword().put(user.getHasCashPassword());
			sp.phone().put(phone);
			if (user.getRecommendStatus() != null
					&& user.getRecommendStatus().equals("0")) {
				Intent intent = new Intent(this,
						InputSecommendCodeActivity_.class);
				startActivity(intent);
				finish();
			} else {
				Intent intent = new Intent(this, Main2Activity_.class);
				startActivity(intent);
				finish();
			}

		} else {
			showTxt(res.getMessage());
		}
		closeDialog();
	}

	// 发送验证码按钮
	@Click
	void btn_send() {
		boolean bol = NetworkUtil.checkNetworkInfo(this);
		if (!bol) {
			showTxt("请检查网络是否正常！");
			return;
		}
		phone = edit_phone.getText().toString();
		if (phone == null || phone.equals("")) {
			showTxt("请输入手机号");
			return;
		}

		boolean isPhone = CommonUtils.isPhone(phone);
		if (!isPhone) {
			showTxt("手机号码格式不对!");
			return;
		}
		sendCode(phone);
	}

	@Background
	void sendCode(String phone) {
		timeCode.start();
		BaseJsonToModel model = finder.getRegistCode(phone, tm.getDeviceId());
		if (model.getResultCode().equals(ReturnCode.SUCCEED)) {
		} else {
			showTxt(model.getResultMessage());
		}
	}

	// 倒计时实现类
	class TimeCode extends CountDownTimer {

		public TimeCode(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		}

		@Override
		public void onFinish() {
			btn_send.setEnabled(true);
			btn_send.setBackground(getResources().getDrawable(
					R.drawable.btn_select));
			btn_send.setText("重获验证码");
			edit_phone.setEnabled(true);
		}

		@Override
		public void onTick(long arg0) {
			btn_send.setBackgroundResource(R.color.text3_color);
			btn_send.setEnabled(false);
			btn_send.setText(arg0 / 1000 + "秒");
			edit_phone.setEnabled(false);
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		AVAnalytics.onResume(this);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		AVAnalytics.onPause(this);
	}

	@UiThread
	void showTxt(String txt) {
		toast.ShowToast(txt);
	}

	// 服务协议
	@Click
	void txt_service() {
		Intent intent = new Intent(this, ProtocalActivity_.class);
		startActivity(intent);
	}

}
